﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using LitJson;

[AddComponentMenu("PUEX/Affector/UV/SubUVOverLifetime")]
public class PUEXSubUVOverLifetimeAffector : PUEXAffector {
	
	#region - Editable property
	public PUEXDynamicAttribute frameOverLifetime;
	public bool useEmitterTime;
	#endregion
	
	#region - Lifecycle
	public PUEXSubUVOverLifetimeAffector ()
	{
		frameOverLifetime = PUEXDynamicAttribute.GenerateCurved (0f, 1f);
		useEmitterTime = false;
	}
	#endregion

	#region - Update
	public override void update (float dt, PUEXParticle particle)
	{
		float t = particle.timeFraction;
		if (useEmitterTime)
			t = inTrigger () ? triggerTimeFraction : ownerEmitter.timeFraction;

		int ut = (int)ownerEmitter.uvTiles.x > 0 ? (int)ownerEmitter.uvTiles.x : 1;
		int vt = (int)ownerEmitter.uvTiles.y > 0 ? (int)ownerEmitter.uvTiles.y : 1;

		float f = frameOverLifetime.getValue (t);
		f = f - (int)f;
		int frame = (int)(f * (ut * vt));
		particle.uvOffset = particle.originalUVOffset + new Vector2 (frame % ut, frame / ut);
	}
	#endregion
	
	#region - Param property
	public override void updateParams (PUEXParticleSystem system)
	{
		frameOverLifetime.parameterize (system);
	}
	#endregion

	#region - Serialization
	public override JsonData save (JsonData emitterData, JsonData systemData)
	{
		JsonData ret = base.save (emitterData, systemData);

		ret ["frame_over_lifetime"] = PUEXUtils.serializeDynamicAttribute(frameOverLifetime);
		ret ["use_emitter_time"] = useEmitterTime;
		
		return ret;
	}
	#endregion

}
